import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { TagServiceProxy, PictureDto, TagDto, CreatePictureInput, PictureServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import { FileUploader } from 'ng2-file-upload';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    selector: 'createOrEditPictureModal',
    templateUrl: './create-or-edit-picture-modal.component.html',
    styles: []
})
export class CreateOrEditPictureModalComponent extends AppComponentBase {

    @ViewChild('nameInput') nameInput: ElementRef;
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();


    active = false;
    saving = false;       //

    uploadUrl: string;
    uploadedFiles: any[] = [];
    //uploader
    public uploader: FileUploader;

    picture: PictureDto;

    constructor(
        injector: Injector,
        private _pictureService: PictureServiceProxy,
        private _tagService: TagServiceProxy
    ) {
        super(injector);
        this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/Upload/UploadFile';

    }

    show(pictureId?: number): void {
        this.picture = new PictureDto();
        this.uploader = new FileUploader({
            url: this.uploadUrl,
            method: 'POST',
            itemAlias: 'uploadedfile'
        });
        if (!pictureId || pictureId === undefined) {
            this.active = true;
            this.modal.show();
        } else {
            this._pictureService.get(pictureId).subscribe(Result => {
                this.picture = Result;

                this.modal.show();
            });
        }

    }
    onShown(): void {
        this.active = true;
        // $(this.nameInput.nativeElement).focus();

        // this.organizationUnitTree.data = <IOrganizationUnitsTreeComponentData>{
        //     allOrganizationUnits: this.allOrganizationUnits,
        //     selectedOrganizationUnits: this.memberedOrganizationUnits
        // };
    }

    save(): void {
        let input = new CreatePictureInput();
        input = this.picture;

        this.saving = true;
        if (input.id === 0 || input.id === undefined) {
            this._pictureService.create(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        } else {
            this._pictureService.update(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        }
    }

    // upload completed event
    onUpload(event): void {
        for (const file of event.files) {
            this.uploadedFiles = new Array<any>();
            this.uploadedFiles.push(file);
        }
        const jsonResult = JSON.parse(event.xhr.response);
        this.picture.url = jsonResult.result;
    }

    onBeforeSend(event): void {
        event.xhr.setRequestHeader('Authorization', 'Bearer ' + abp.auth.getToken());
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}


